package com.jiang.jetpackdemo.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.fragment.FavoritesPicFragment
import com.jiang.jetpackdemo.model.FavoritesModel
import com.jiang.jetpackdemo.utils.loadPicFromNet

class FavoritesAdapter(
    private val context: Context,
    private val list: MutableList<FavoritesModel>,
    private val type: FavoritesPicFragment.Type
) : RecyclerView.Adapter<FavoritesAdapter.ViewHolder>() {
    class ViewHolder(view: View, type: FavoritesPicFragment.Type) : RecyclerView.ViewHolder(view) {
        val iv: ImageView = view.findViewById(R.id.iv_pic)
        val btn: Button = view.findViewById(R.id.btn)

        val tv_t: TextView? = view.findViewById(R.id.tv_t)
        val tv_d: TextView? = view.findViewById(R.id.tv_d)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val viewHolder = ViewHolder(
            LayoutInflater.from(context).inflate(getLayoutId(type), parent, false),
            type
        )
        return viewHolder
    }

    private fun getLayoutId(type: FavoritesPicFragment.Type): Int {
        return when (type) {
            FavoritesPicFragment.Type.PICTURE -> R.layout.item_pic
            FavoritesPicFragment.Type.VIDEO -> R.layout.item_rv_play_video
            else -> R.layout.item_rv_news
        }
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val favoritesModel = list[position]
        holder.iv.loadPicFromNet(favoritesModel.imgUrl)
        holder.btn.setOnLongClickListener {
            onLongClick(position)
            true
        }
        holder.tv_t?.text = favoritesModel.title
        holder.tv_d?.text = favoritesModel.des
        holder.btn.setOnClickListener { onClick(holder.absoluteAdapterPosition) }
    }

    private var onLongClick: ((Int) -> Unit) = {}
    fun setOnLongClick(onLongClick: ((Int) -> Unit)) {
        this.onLongClick = onLongClick
    }

    private var onClick: ((Int) -> Unit) = {}
    fun setOnClick(onLongClick: ((Int) -> Unit)) {
        this.onClick = onLongClick
    }
}